package top.jsjkxyjs.blackbox.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.jsjkxyjs.blackbox.common.DatabaseAwareness.DatabaseAwareness;
import top.jsjkxyjs.blackbox.entity.Car;
import top.jsjkxyjs.blackbox.entity.User;
import top.jsjkxyjs.blackbox.service.CarService;
import top.jsjkxyjs.blackbox.service.DevBindService;
import top.jsjkxyjs.blackbox.service.IotService;
import top.jsjkxyjs.blackbox.service.UserService;
import top.jsjkxyjs.blackbox.utils.MD5;
import top.jsjkxyjs.blackbox.utils.Msg;
import top.jsjkxyjs.blackbox.utils.Utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Controller
public class CommonController {
	@Autowired
	UserService userService;
	@Autowired
	CarService carService;
	@Autowired
	DevBindService devBindService;
	@Autowired
	DatabaseAwareness databaseAwareness;
	@Autowired
	IotService iotService;

	@RequestMapping({"/", "/login"})
	public String login(HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) {
		User user = new User();
		for (Cookie cookie : request.getCookies()) {
			if ("phone".equals(cookie.getName())) {
				user.setPhone(cookie.getValue());
			}
			if ("password".equals(cookie.getName())) {
				user.setPassWord(cookie.getValue());
			}
		}
		if (user.getPhone() != null && user.getPassWord() != null) {
			user = userService.checkLogin(user);
			if (user != null) {
				httpSession.setAttribute("user", user);
				Cookie phone = new Cookie("phone", user.getPhone());
				phone.setMaxAge(7 * 24 * 60 * 60);
				phone.setHttpOnly(true);
				Cookie password = new Cookie("password", user.getPassWord());
				password.setMaxAge(7 * 24 * 60 * 60);
				password.setHttpOnly(true);
				response.addCookie(phone);
				response.addCookie(password);
				if (user.getRole() == 1) {
					return "pages/user/index";
				} else {
					return "pages/service/index";
				}
			}
		}

		user = (User) httpSession.getAttribute("user");
		if (user != null) {
			if (user.getRole() == 1) {
				return "pages/user/index";
			} else {
				return "pages/service/index";
			}
		} else {
			return "login";
		}
	}

	@PostMapping("/dologin")
	@ResponseBody
	public Msg doLogin(User user, HttpSession httpSession, HttpServletResponse response) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		user.setPassWord(MD5.EncoderByMd5(user.getPassWord()));
		user = userService.checkLogin(user);
		if (user != null) {
			httpSession.setAttribute("user", user);
			Cookie phone = new Cookie("phone", user.getPhone());
			phone.setMaxAge(7 * 24 * 60 * 60);
			phone.setHttpOnly(true);
			Cookie password = new Cookie("password", user.getPassWord());
			password.setMaxAge(7 * 24 * 60 * 60);
			password.setHttpOnly(true);
			response.addCookie(phone);
			response.addCookie(password);
			return Msg.success();
		} else {
			return Msg.tips("用户名或密码不正确！", 400);
		}
	}

	@PostMapping("/register")
	@ResponseBody
	public Msg register(User user, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		user.setRole(1);
		if (!Utils.isMobile(user.getPhone()) || !Utils.isMobile(user.getEmergencyPhone())) {
			return Msg.tips("手机号码输入不正确", 400);
		} else {
			if (!userService.foundUser(user.getPhone())) {
				user.setPassWord(MD5.EncoderByMd5(user.getPassWord()));
				user = userService.register(user);
				session.setAttribute("user", user);
				return Msg.success();
			} else {
				return Msg.tips("您已经注册过了，请登陆！", 400);
			}
		}
	}

	@RequestMapping("/index")
	public String index(HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		if (user.getRole() == 1) {
			List<Car> carNumbers = carService.getUserAllCars(user);
			model.addAttribute("carNumbers", carNumbers.size());
			int iotNumbers = devBindService.countUsersAllIots(user.getId());
			model.addAttribute("iotNumbers", iotNumbers);
			int iotsDatasNumber = devBindService.countUsersAllIotsDatas(user.getId());
			model.addAttribute("iotsDatasNumber", iotsDatasNumber);
			return "pages/user/index";
		} else {
			int carNumbers = carService.getAllCars();
			model.addAttribute("carNumbers", carNumbers);
			int devNumbers = devBindService.getAllIots();
			model.addAttribute("iotNumbers", devNumbers);
			int iotsDatasNumber = iotService.getiotsDatasNumber();
			model.addAttribute("iotsDatasNumber", iotsDatasNumber);
			return "pages/service/index";
		}
	}

	@RequestMapping("/loginout")
	public String loginout(HttpSession session, HttpServletResponse response) {
		Cookie phone = new Cookie("phone", "");
		phone.setMaxAge(0);
		phone.setHttpOnly(true);
		Cookie password = new Cookie("password", "");
		password.setMaxAge(0);
		password.setHttpOnly(true);
		response.addCookie(phone);
		response.addCookie(password);
		session.removeAttribute("user");
		return "login";
	}

	@RequestMapping("/databaseawareness")
	public void databaseawareness() throws InterruptedException {
		databaseAwareness.perception();
	}
}
